package com.okok.service;

import java.util.Date;

import com.common.Const;
import com.entity.myInterface.TokenRepository;
import com.common.springside.Digests;
import com.common.springside.Encodes;
import com.okok.entity.User;
import com.shiro.entity.Token;
import com.shiro.services.AbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.util.DateUtil;
/**
 * 令牌Service
 * @author Eason
 *
 */
@Service
public class TokenService extends AbstractService {

	private static Logger logger = LoggerFactory.getLogger(TokenService.class);
	
	@Autowired
	private TokenRepository tokenRepository;

	/**
	 * 用户登录,生成token
	 * 逻辑：
	 * 
	 * @param user
	 * @param op
	 * @return
	 */
	public Token newToken(User user, String op) {
		// 更新该user的所有的其他token valid = false
		this.tokenRepository.unvalidUserTokens(user, op);

		Token token = new Token();
		token.setCreator(user.getLoginName());
		token.setModifier(user.getLoginName());
		
		// 设置有效天数
		token.setValidDays( Const._DEF_VALID_DAYS );
		
		// 根据有效天数设置到期日
		token.setValidTo(DateUtil.addDay( new Date(), Const._DEF_VALID_DAYS));
		
		// 生成token
		String tokenOrigin = user.getLoginName() + user.getLoginPwd() +  7;
		String tokenStr = buildToken(tokenOrigin);
		
		//用tokenStr做种子,生成secret
		String secret = buildToken(tokenStr);
		
		token.setToken( tokenStr ) ;
		token.setUser(user);
		token.setSecret(secret);
		token = this.tokenRepository.save(token);
		
		return token;
	}

	private String buildToken(String tokenOrigin) {
		byte[] salt = Digests.generateSalt(Const.SALT_SIZE);
		byte[] tokenBytes = Digests.sha1(tokenOrigin.getBytes(), salt, Const.HASH_INTERATIONS);
		String tokenStr = Encodes.encodeHex( tokenBytes );
		return tokenStr;
	}

}